/* 用户信息模块 */

import { getToken, setToken, removeToken } from '@/utils/auth'
import { getUserInfo, login, getUserDetailById } from '@/api/user.js'
// 状态
const state = {
  token: getToken(),
  userInfo: {}
}
// 修改状态
const mutations = {
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  removeToken(state) {
    state.token = null
    removeToken()
  },
  setUserInfo(state, userInfo) {
    state.userInfo = { ...userInfo }
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
// 执行异步
const actions = {
  async login(context, data) {
    const result = await login(data)
    // 失败情况在响应拦截器中处理过了,因此此处不需要处理
    context.commit('setToken', result)
  },
  async getUserInfo(context) {
    const result = await getUserInfo()
    const baseInfo = await getUserDetailById(result.userId) // 为了获取头像
    // 将两个接口结果合并
    context.commit('setUserInfo', { ...result, ...baseInfo })
    return result // 这里为什么要返回 为后面埋下伏笔
  },
  logout(context) {
    context.commit('removeToken')
    context.commit('removeUserInfo')
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
